/*
 * Copyright 2011-2011 Tiago da Fonseca Frazao  All rights reserved.
 */
package mz.co.framework.context;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

import mz.co.framework.error.SystemException;
import mz.co.research.shared.model.LifeCycleEntity;

import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

public class LifeCycleInterceptor extends EmptyInterceptor {

	/**
	 * Serial Version UID
	 */
	private static final long serialVersionUID = -8723757994961844089L;

	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {

		boolean changed = false;

		try {

			if (entity instanceof LifeCycleEntity) {
				IUserContext context = UserContextHolder.getContext();
				Date cal = Calendar.getInstance().getTime();
				for (int i = 0; i < propertyNames.length; i++) {
					if ("creationDate".equals(propertyNames[i])) {
						state[i] = cal;
						changed = true;
					} else if ("createdBy".equals(propertyNames[i])) {
						state[i] = context.getId();
						changed = true;
					} else if ("activationDate".equals(propertyNames[i])) {
						state[i] = cal;
						changed = true;
					} else if ("activatedBy".equals(propertyNames[i])) {
						state[i] = context.getId();
						changed = true;
					} else if ("active".equals(propertyNames[i])) {
						state[i] = Boolean.valueOf(true);
						changed = true;
					} else if ("ip".equals(propertyNames[i])) {
						state[i] = context.getIp();
						changed = true;
					}
				}
			}

		} catch (SystemException se) {
			throw new CallbackException(se);
		}

		return changed;
	}

	@Override
	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		return super.onFlushDirty(entity, id, currentState, previousState,
				propertyNames, types);
	}
}
